/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.repair.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.common.config.BladeOssRuleExt;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseEntity;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.ObjectUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.repair.dto.*;
import org.springblade.modules.repair.dto.elevator.ElevatorSearchDTO;
import org.springblade.modules.repair.entity.*;
import org.springblade.modules.repair.enums.*;
import org.springblade.modules.repair.mapper.ElevatorMapper;
import org.springblade.modules.repair.mapper.MaintainPlanContentMapper;
import org.springblade.modules.repair.service.*;
import org.springblade.modules.repair.vo.*;
import org.springblade.modules.repair.vo.elevator.ElevatorFloorVo;
import org.springblade.modules.repair.vo.elevator.ElevatorHealthVo;
import org.springblade.modules.repair.vo.elevator.ElevatorPartWorkVo;
import org.springblade.modules.repair.vo.elevator.ElevatorPlanVo;
import org.springblade.modules.repair.vo.part.PartWordUrlVo;
import org.springblade.modules.resource.builder.oss.OssBuilder;
import org.springblade.modules.system.entity.Dict;
import org.springblade.modules.system.service.IDictService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 电梯信息 服务实现类
 *
 * @author BladeX
 * @since 2021-05-21
 */
@Service
public class ElevatorServiceImpl extends BaseServiceImpl<ElevatorMapper, Elevator> implements IElevatorService {

	@Resource
	private ElevatorDetailService elevatorDetailService;

	@Resource
	private IElevatorPlanStatusService elevatorPlanStatusService;

	@Resource
	private MaintainPlanContentMapper maintainPlanContentMapper;

	@Resource
	private IElevatorMalfunctionDayService elevatorMalfunctionDayService;

	@Resource
	private IMaintainMalfunctionLogService maintainMalfunctionLogService;

	@Resource
	private IDictService dictService;

	@Resource
	private ElevatorDriveModeService elevatorDriveModeService;

	@Resource
	private IElevatorScoreService elevatorScoreService;

	@Resource
	private OssBuilder ossBuilder;

	@Resource
	@Lazy
	private IMaintainPlanContentService planContentService;

	@Resource
	@Lazy
	private IBuildingUserService buildingUserService;

	@Autowired
	@Lazy
	private IElevatorExtService elevatorExtService;

	@Resource
	@Lazy
	private MaintainPartsWorkService maintainPartsWorkService;

	@Resource
	@Lazy
	private IMaintainPlanContentUserService maintainPlanContentUserService;

	@Resource
	private RelationAliasService relationAliasService;

	@Autowired
	private IElevatorAttachmentService elevatorAttachmentService;

	@Autowired
	private IBuildingFloorElevatorService buildingFloorElevatorService;

	@Autowired
	private IElevatorFieldVService elevatorFieldVService;
	@Autowired
	private IElevatorAttachmentHistoryService elevatorAttachmentHistoryService;

	@Autowired
	@Lazy
	private IElevatorPartsStructureTemplateRelationService elevatorPartsStructureTemplateRelationService;

	@Autowired
	private IElevatorFloorStandTemplateService elevatorFloorStandTemplateService;

	/**
	 * 电梯状态正常运营标识
	 */
	private final static Integer ELEVATOR_STATUS = 1;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean update(Elevator elevator) {

		ElevatorPlanStatus elevatorPlanStatus = elevatorPlanStatusService.getOne(Wrappers.<ElevatorPlanStatus>lambdaQuery().eq(ElevatorPlanStatus::getElevatorId, elevator.getId()));
		Integer typeStatus = maintainPlanContentMapper.selectById(elevator.getPlanId()).getTypeStatus();

		if (!elevator.getIsStop().equals(ELEVATOR_STATUS)) {
			elevatorPlanStatus.setPlanId(elevator.getPlanId());
			elevatorPlanStatus.setPlanStatus(typeStatus);
			/*更新电梯统计信息*/
			ElevatorMalfunctionDay elevatorMalfunctionDay = elevatorMalfunctionDayService.getOne(Wrappers.<ElevatorMalfunctionDay>lambdaQuery().eq(ElevatorMalfunctionDay::getElevatorId, elevator.getId()).between(ElevatorMalfunctionDay::getCreateTime, DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date())));
			if (elevatorMalfunctionDay == null) {
				elevatorMalfunctionDay = new ElevatorMalfunctionDay();
				elevatorMalfunctionDay.setWxStopCounts(0);
				elevatorMalfunctionDay.setByStopCounts(0);
				elevatorMalfunctionDay.setElevatorId(elevator.getId());
				elevatorMalfunctionDay.setBuildingId(this.getById(elevator.getId()).getBuildingId());
			}
			if (typeStatus == MaintainPlanContentEnum.MAINTAIN_BY.getId()) {
				elevatorMalfunctionDay.setByStopCounts(Convert.toInt(elevatorMalfunctionDay.getByStopCounts(), 0) + 1);
			} else if (typeStatus == MaintainPlanContentEnum.MAINTAIN_WX.getId()) {
				elevatorMalfunctionDay.setWxStopCounts(Convert.toInt(elevatorMalfunctionDay.getWxStopCounts(), 0) + 1);
			}
			elevatorMalfunctionDayService.saveOrUpdate(elevatorMalfunctionDay);

			/*日志维修停梯标识*/
			Integer status = 2;

		} else {
			elevatorPlanStatus.setPlanId(0L);
			elevatorPlanStatus.setPlanStatus(MaintainPlanContentEnum.MAINTAIN_ZC.getId());

		}
		elevatorPlanStatusService.updateById(elevatorPlanStatus);
		return this.updateById(elevator);
	}

	@Override
	public List<ListElevatorVO> listElevator(Long buildingId, String elevatorName) {
		return baseMapper.listElevator(buildingId, elevatorName);
	}

	@Override
	public ElevatorDetailVO selectElevatorDetail(Long elevatorId) {
		if (elevatorId == null) {
			throw new ServiceException("电梯id不能为空");
		}
		ElevatorDetailVO elevatorDetailVO = baseMapper.selectElevatorDetail(elevatorId);
		elevatorDetailVO.setEstateUserList(baseMapper.selectEstateElevatorUser(elevatorId));
		if (Func.isNotEmpty(elevatorDetailVO)) {
			// 项目别名
			List<RelationAlias> relationAliases = relationAliasService.list(new LambdaQueryWrapper<RelationAlias>()
				.eq(RelationAlias::getRelationId, elevatorDetailVO.getBuildingId())
				.eq(BaseEntity::getIsDeleted, 0)
			);
			elevatorDetailVO.setRelationAlias(relationAliases);
		}

		ElevatorFieldV fieldV = elevatorFieldVService.getByElevaotrId(elevatorId);
		elevatorDetailVO.setFieldV(fieldV);

		//使用附件
		List<ElevatorAttachmentHistory> attachmentList = elevatorAttachmentHistoryService.list(Wrappers.<ElevatorAttachmentHistory>lambdaQuery().eq(ElevatorAttachmentHistory::getElevatorId, elevatorId).eq(ElevatorAttachmentHistory::getStatus, ElevatorAttachmentEnum.IMG.getStatus()).orderByDesc(ElevatorAttachmentHistory::getCreateTime).last("LIMIT 1"));
		elevatorDetailVO.setCertificateLists(attachmentList);

		//使用铭牌
		List<ElevatorAttachmentHistory> nameAttachmentList = elevatorAttachmentHistoryService.list(Wrappers.<ElevatorAttachmentHistory>lambdaQuery().eq(ElevatorAttachmentHistory::getElevatorId, elevatorId).eq(ElevatorAttachmentHistory::getStatus, ElevatorAttachmentEnum.NAME.getStatus()).orderByDesc(ElevatorAttachmentHistory::getCreateTime).last("LIMIT 1"));
		elevatorDetailVO.setNameAttachmentList(nameAttachmentList);

		//楼栋信息
		if (elevatorDetailVO.getFloorElevatorId() != null) {
			BuildingFloorElevator floorElevator = buildingFloorElevatorService.getById(elevatorDetailVO.getFloorElevatorId());
			if (floorElevator != null) {
				elevatorDetailVO.setFloorNums(floorElevator.getFloorNums());
				elevatorDetailVO.setFloorAllNum(floorElevator.getFloorAllNum());
			}
		}

		//电梯维保信息
		Elevator elevator = this.getById(elevatorId);
		elevatorDetailVO.setWbPhoneImg(elevator.getWbPhoneImg());
		elevatorDetailVO.setWbExtUrl(elevator.getWbExtUrl());
		elevatorDetailVO.setFloorDoors(elevator.getFloorDoors());
		elevatorDetailVO.setFloorPlatforms(elevator.getFloorPlatforms());
		elevatorDetailVO.setFloorTier(elevator.getFloorTier());
		elevatorDetailVO.setBxExtUrl(elevator.getBxExtUrl());
		//识别代码贴纸附近
		ElevatorDetail elevatorDetail = elevatorDetailService.getOne(Wrappers.<ElevatorDetail>lambdaQuery().eq(ElevatorDetail::getElevatorId, elevatorId));
		elevatorDetailVO.setElevatorNumImg(elevatorDetail.getElevatorNumImg());
		elevatorDetailVO.setElevatorNumImgDate(elevatorDetail.getElevatorNumImgDate());
		elevatorDetailVO.setElevatorNum(elevatorDetail.getElevatorNum());
		return elevatorDetailVO;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean updateElevatorDetail(Long id, ElevatorDetailDTO elevatorDetailDTO) {
		Elevator oldElevator = getById(id);
		if (Func.isEmpty(oldElevator)) {
			throw new ServiceException("电梯不存在");
		}
		Elevator elevator = new Elevator();
		BeanUtil.copyProperties(elevatorDetailDTO, elevator);
		elevator.setId(id);
		ElevatorDetail elevatorDetail = new ElevatorDetail();
		BeanUtil.copyProperties(elevatorDetailDTO, elevatorDetail);
		ElevatorAudit elevatorAudit = new ElevatorAudit();
		elevatorAudit.setElevatorId(id);
		Long modeId = null;
		//更新设备信息
		if (elevatorDetailDTO.getFieldV() != null) {
			ElevatorFieldV fieldV = elevatorDetailDTO.getFieldV();
			ElevatorFieldV elevatorFieldV = elevatorFieldVService.getByElevaotrId(id);
			fieldV.setDriveModeId(elevatorDetail.getElevatorUseType());
			if (ObjectUtil.isNotEmpty(elevatorFieldV)) {
				fieldV.setId(elevatorFieldV.getId());
				fieldV.setTenantId(elevatorFieldV.getTenantId());
			}
			elevatorFieldVService.saveOrUpdate(fieldV);
		}

		// 记录使用证标志
		if (elevatorDetailDTO.getCertificateLists() != null && elevatorDetailDTO.getCertificateLists().size() > 0) {
			List<ElevatorAttachmentHistory> historyList = elevatorAttachmentHistoryService.list(Wrappers.<ElevatorAttachmentHistory>lambdaQuery().eq(ElevatorAttachmentHistory::getElevatorId, id).eq(ElevatorAttachmentHistory::getStatus, ElevatorAttachmentEnum.IMG.getStatus()));
			List<String> urls = new ArrayList<>(100);
			for (ElevatorAttachmentHistory elevatorAttachmentHistory : historyList) {
				com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(Convert.toStr(elevatorAttachmentHistory.getAttachment(), "{}"));
				if (jsonObject.size() > 0) {
					urls.add(Convert.toStr(jsonObject.get("url")));
				}
			}
			List<ElevatorAttachmentHistory> saveList = new ArrayList<>(16);
			for (ElevatorAttachmentHistory elevatorAttachmentHistory : elevatorDetailDTO.getCertificateLists()) {
				com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(Convert.toStr(elevatorAttachmentHistory.getAttachment(), "{}"));
				if (jsonObject.size() > 0) {
					if (!urls.contains(Convert.toStr(jsonObject.get("url")))) {
						ElevatorAttachmentHistory elevatorAttachmentHistory1 = new ElevatorAttachmentHistory();
						elevatorAttachmentHistory1.setStatus(ElevatorAttachmentEnum.IMG.getStatus());
						elevatorAttachmentHistory1.setAttachment(elevatorAttachmentHistory.getAttachment());
						elevatorAttachmentHistory1.setElevatorId(id);
						saveList.add(elevatorAttachmentHistory1);
					}
				}
			}
			elevatorAttachmentHistoryService.saveBatch(saveList);
		}

		// 记录铭牌并且校验重复
		if (elevatorDetailDTO.getNameAttachmentList() != null && elevatorDetailDTO.getNameAttachmentList().size() > 0) {
			List<ElevatorAttachmentHistory> historyList = elevatorAttachmentHistoryService.list(Wrappers.<ElevatorAttachmentHistory>lambdaQuery().eq(ElevatorAttachmentHistory::getElevatorId, id).eq(ElevatorAttachmentHistory::getStatus, ElevatorAttachmentEnum.NAME.getStatus()));
			List<String> urls = new ArrayList<>(100);
			for (ElevatorAttachmentHistory elevatorAttachmentHistory : historyList) {
				JSONObject jsonObject = JSON.parseObject(Convert.toStr(elevatorAttachmentHistory.getAttachment(), "{}"));
				if (jsonObject.size() > 0) {
					urls.add(Convert.toStr(jsonObject.get("url")));
				}
			}
			List<ElevatorAttachmentHistory> saveList = new ArrayList<>(16);
			for (ElevatorAttachmentHistory elevatorAttachmentHistory : elevatorDetailDTO.getNameAttachmentList()) {
				JSONObject jsonObject = JSON.parseObject(Convert.toStr(elevatorAttachmentHistory.getAttachment(), "{}"));
				if (jsonObject.size() > 0) {
					if (!urls.contains(Convert.toStr(jsonObject.get("url")))) {
						elevatorAttachmentHistory.setStatus(ElevatorAttachmentEnum.NAME.getStatus());
						elevatorAttachmentHistory.setElevatorId(id);
						saveList.add(elevatorAttachmentHistory);
					}
				}
			}
			elevatorAttachmentHistoryService.saveBatch(saveList);
		}

		if (!StringUtil.isEmpty(elevator.getPrivateNum())) {
			// 检查电梯编码
			checkPrivateNum(elevator.getPrivateNum(), elevator.getId());
			//获取电梯年检时间
//			String auditTime = elevatorAuditService.getElevatorAuditTimeByPrivateNum(elevator.getPrivateNum());
//			elevator.setElevatorAudit(auditTime);
//			elevatorAudit.setAuditTime(auditTime);
			//驱动方式
			modeId = getElevatorDriveModeByPrivateNum(elevator.getPrivateNum());
			elevatorDetail.setElevatorUseType(modeId == null ? elevatorDetailDTO.getElevatorUseType() : modeId);
			// 制造日期
			Date madeDate = getElevatorMadeDate(elevator.getPrivateNum());
			elevatorDetail.setMadeDate(madeDate == null ? elevatorDetailDTO.getMadeDate() : madeDate);
		} else {
			elevator.setPrivateNum(null);
			elevator.setIsComplete(false);
			elevatorDetail.setElevatorUseType(elevatorDetailDTO.getElevatorUseType());
			elevatorDetail.setMadeDate(elevatorDetailDTO.getMadeDate());
		}


		//2024-07-26 新增电梯维保安装,改装大修信息-新增历史记录
		Elevator elevator2 = this.getById(id);
		if (elevatorDetailDTO.getWbPhoneImg() != null && elevatorDetailDTO.getWbPhoneImg().size() > 0) {
			List<PartWordUrlVo> wordUrlVos = filterExis(elevator2.getWbPhoneImg(), elevatorDetailDTO.getWbPhoneImg());
			for (PartWordUrlVo partWordUrlVo : wordUrlVos) {
				elevator.setWbPhoneImgDate(new Date());
				ElevatorAttachmentHistory wbPhoneImgHistory = new ElevatorAttachmentHistory();
				wbPhoneImgHistory.setElevatorId(id);
				wbPhoneImgHistory.setAttachment(JSON.toJSONString(partWordUrlVo));
				wbPhoneImgHistory.setStatus(ElevatorAttachmentEnum.WB_PHONE_IMG.getStatus());
				elevatorAttachmentHistoryService.save(wbPhoneImgHistory);
			}
		}
		if (elevatorDetailDTO.getWbExtUrl() != null && elevatorDetailDTO.getWbExtUrl().size() > 0) {
			List<PartWordUrlVo> wordUrlVos = filterExis(elevator2.getWbExtUrl(), elevatorDetailDTO.getWbExtUrl());
			for (PartWordUrlVo partWordUrlVo : wordUrlVos) {
				elevator.setWbExtUrlDate(new Date());
				ElevatorAttachmentHistory wbExtUrlImgHistory = new ElevatorAttachmentHistory();
				wbExtUrlImgHistory.setElevatorId(id);
				wbExtUrlImgHistory.setAttachment(JSON.toJSONString(partWordUrlVo));
				wbExtUrlImgHistory.setStatus(ElevatorAttachmentEnum.WB_EXT_IMG.getStatus());
				elevatorAttachmentHistoryService.save(wbExtUrlImgHistory);
			}
		}

		//新增保险
		if (elevatorDetailDTO.getBxExtUrl() != null && elevatorDetailDTO.getBxExtUrl().size() > 0) {
			List<PartWordUrlVo> wordUrlVos = filterExis(elevator2.getBxExtUrl(), elevatorDetailDTO.getBxExtUrl());
			for (PartWordUrlVo partWordUrlVo : wordUrlVos) {
				elevator.setBxExtUrlDate(new Date());
				ElevatorAttachmentHistory wbExtUrlImgHistory = new ElevatorAttachmentHistory();
				wbExtUrlImgHistory.setElevatorId(id);
				wbExtUrlImgHistory.setAttachment(JSON.toJSONString(partWordUrlVo));
				wbExtUrlImgHistory.setStatus(ElevatorAttachmentEnum.BX_IMG.getStatus());
				elevatorAttachmentHistoryService.save(wbExtUrlImgHistory);
			}
		}

		if (elevatorDetailDTO.getElevatorNumImg() != null && elevatorDetailDTO.getElevatorNumImg().size() > 0) {
			ElevatorDetail elevatorDetail3 = elevatorDetailService.getOne(Wrappers.<ElevatorDetail>lambdaQuery().eq(ElevatorDetail::getElevatorId, id));
			List<PartWordUrlVo> wordUrlVos = filterExis(elevatorDetail3.getElevatorNumImg(), elevatorDetailDTO.getElevatorNumImg());
			for (PartWordUrlVo partWordUrlVo : wordUrlVos) {
				elevatorDetail.setElevatorNumImgDate(new Date());
				ElevatorAttachmentHistory elevatorNumImgHistory = new ElevatorAttachmentHistory();
				elevatorNumImgHistory.setElevatorId(id);
				elevatorNumImgHistory.setAttachment(JSON.toJSONString(partWordUrlVo));
				elevatorNumImgHistory.setStatus(ElevatorAttachmentEnum.ELEVATOR_NUM_IMG.getStatus());
				elevatorAttachmentHistoryService.save(elevatorNumImgHistory);
			}
		}
		elevatorDetailService.update(elevatorDetail, new LambdaUpdateWrapper<ElevatorDetail>().eq(ElevatorDetail::getElevatorId, id));
		ElevatorDetail elevatorDetail2 = elevatorDetailService.getOne(Wrappers.<ElevatorDetail>lambdaQuery().eq(ElevatorDetail::getElevatorId, id));
		if (modeId != null && elevatorIsComplete(elevatorDetail2)) {
			elevator.setIsComplete(true);
		} else {
			elevator.setIsComplete(false);
		}

		elevatorIntact(elevatorDetailDTO, elevator);

		this.updateById(elevator);

		// 同步层站结构
		if (!(floorPlatformsCompare(oldElevator.getFloorPlatforms(), elevator.getFloorPlatforms())
			&& floorDoorsCompare(oldElevator.getFloorDoors(), elevator.getFloorDoors()))) {
			elevatorFloorStandTemplateService.syncElevatorFloorStandTemplate(id, elevator.getFloorPlatforms(), elevator.getFloorDoors());
		}
		return Boolean.TRUE;
	}

//	@Override
//	public IPage<PlanContentStatisticalDetailVo> getDisScheduleOfGroupIds(IPage<PlanContentStatisticalDetailVo> page, PlanContentStatisticalSearchDTO planContentStatisticalSearchDTO) {
//		return baseMapper.getDisScheduleOfGroupIds(page,planContentStatisticalSearchDTO);
//	}


	public ElevatorVO selectElevByPrivateNum(String privateNum, Long elevatorId) {
		return baseMapper.selectElevByPrivateNum(privateNum, elevatorId);
	}


	/**
	 * @Date 9:01 2021/3/25
	 * @Description {
	 * // 检查电梯编码是否重复
	 * }
	 * @Author lsay
	 **/
	private void checkPrivateNum(String privateNum, Long elevatorId) {
		if (ObjectUtil.isNotEmpty(privateNum)) {
			if (privateNum.length() < 4) {
				throw new ServiceException("设备编码格式异常");
			}
			ElevatorVO elevatorVO = this.selectElevByPrivateNum(privateNum, elevatorId);
			if (Func.notNull(elevatorVO)) {
				String address = elevatorVO.getBuildingName() + "-" + elevatorVO.getElevatorAddress();
				throw new ServiceException("与现有电梯（" + address + ")编码相同，请确认后再次输入");
			}
		}
	}

	/**
	 * 根据电梯设备代码获取电梯制造日期
	 *
	 * @param privateNum
	 */
	private Date getElevatorMadeDate(String privateNum) {
		Date madeDate = null;
		if (privateNum.length() == 20) {
			// 制造日期
			try {
				madeDate = DateUtil.parse(privateNum.substring(10, 16), "yyyyMM");
			} catch (Exception e) {
				return madeDate;
			}
		}
		return madeDate;
	}

	/**
	 * 根据设备代码前4位获取电梯驱动方式
	 *
	 * @param privateNum
	 * @return
	 */
	private Long getElevatorDriveModeByPrivateNum(String privateNum) {
		ElevatorDriveMode elevatorDriveMode = elevatorDriveModeService.getOne(Wrappers.<ElevatorDriveMode>lambdaQuery().eq(ElevatorDriveMode::getCode, privateNum.length() > 4 ? privateNum.substring(0, 4) : privateNum));
		if (ObjectUtil.isEmpty(elevatorDriveMode)) {
			return null;
		}
		return elevatorDriveMode.getId();
	}

	@Override
	public IPage<ElevatorVO> selectElevatorPage(IPage<ElevatorVO> page, Elevator elevator) {
		return page.setRecords(baseMapper.selectElevatorPage(page, elevator));
	}

	@Override
	public Boolean updateElevatorIsStop(Long elevatorId, Integer isStop) {
		Elevator elevator = this.getById(elevatorId);
		if (Func.isEmpty(elevator)) {
			return false;
		}
		elevator.setIsStop(isStop);
		return this.updateById(elevator);
	}

	@Override
	public IPage<ElevatorDetailVO> getElevatorListByUserDid(ElevatorQueryDTO queryDTO, IPage<ElevatorDetailVO> page) {
		IPage<ElevatorDetailVO> resultList = page.setRecords(baseMapper.getElevatorListByUserDid(queryDTO, page));
		resultList.getRecords().forEach(j -> {
			try {
				Long elevatorId = j.getId();
//				List<String> fulls = new ArrayList<>();
//				fulls.add("isFull");
//				fulls.add("privateNumIsFull");
//				fulls.add("elevatorLatitude");
//				fulls.add("elevatorLongitude");
//				j.setIsFull(CommonUtil.isALLFieldNotNull(j, fulls));
				j.setIsFull(isFull(elevatorId));
			} catch (Exception e) {
				throw new ServiceException("请求处理异常，请稍后重试！");
			}
		});
		return resultList;
	}

	private boolean isOk(BigDecimal bigDecimal) {
		if (Func.isNull(bigDecimal) || bigDecimal.compareTo(new BigDecimal("1.00")) < 0) {
			return false;
		}
		return bigDecimal.compareTo(new BigDecimal("1.00")) == 0;
	}

	public boolean isFull(Long elevatorId) {
		Elevator currentElevator = this.getById(elevatorId);
		BigDecimal jgIntact = currentElevator.getJgIntact();
		BigDecimal wbIntact = currentElevator.getWbIntact();
		BigDecimal bxIntact = currentElevator.getBxIntact();
		BigDecimal sbJsIntact = currentElevator.getSbJsIntact();
		BigDecimal sbZcIntact = currentElevator.getSbZcIntact();
		BigDecimal ccIntact = currentElevator.getCcIntact();
		BigDecimal syIntact = currentElevator.getSyIntact();
		BigDecimal azIntact = currentElevator.getAzIntact();
		BigDecimal twyIntact = currentElevator.getTwyIntact();
		return isOk(jgIntact)
			&& isOk(wbIntact)
			&& isOk(bxIntact)
			&& isOk(sbJsIntact)
			&& isOk(sbZcIntact)
			&& isOk(ccIntact)
			&& isOk(syIntact)
			&& isOk(azIntact)
			&& isOk(twyIntact);
	}

	private Boolean elevatorIsComplete(ElevatorDetail elevatorDetail) {

		if (StrUtil.isEmpty(elevatorDetail.getSecurityGuardName())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getSupportingPower())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getRegisterNumber())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getEquipmentRegisterNumber())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getFloorHigh())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getDoor())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getStand())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getRegistrationAuthority())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getCertificationBody())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getFactoryNumber())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getSpeed())) {
			return false;
		}
		if (elevatorDetail.getMadeDate() == null) {
			return false;
		}
		if (elevatorDetail.getElevatorUseType() == null) {
			return false;
		}
		if (elevatorDetail.getUseType() == null) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getCertNo())) {
			return false;
		}

		if (StrUtil.isEmpty(elevatorDetail.getManufactureNo())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getHoistHeight())) {
			return false;
		}
		return true;
	}

	@Override
	public IPage<ElevatorVO> buildingElevatorList(Long buildingId, IPage<Object> page, String eleName) {
		IPage<ElevatorVO> pages = baseMapper.buildingElevatorList(buildingId, page, eleName);
		return pages;
	}

	@Override
	public SimpleElevatorPlanInfoDTO getSimpleElevatorPlanInfo(Long elevatorId) {
		return baseMapper.getSimpleElevatorPlanInfo(elevatorId);
	}

	/**
	 * copy from maintain_admin project, @lasy
	 *
	 * @return elevator principal count result map
	 */
	@Override
	public Map<String, Integer> selectElevatorPrincipalCount() {
		return baseMapper.selectElevatorPrincipalCount();
	}

	/**
	 * Elevator overview, just some simple calculate
	 *
	 * @return result
	 */
	@Override
	public ElevatorPrincipalStatisticsVO selectElevatorOverview() {
		Map<String, Integer> sourceMap = baseMapper.selectElevatorPrincipalCount();
		if (Func.isNull(sourceMap)) {
			return new ElevatorPrincipalStatisticsVO();
		}

		// get values for simple calculate
		Number inMaintainNum = sourceMap.get("inMaintain");
		Number deptCountNum = sourceMap.get("deptCount");
		Number userCountNum = sourceMap.get("userCount");
		Number auditNum = sourceMap.get("audit");
		Number notAuditNum = sourceMap.get("notAudit");
		int inMaintain = inMaintainNum.intValue();
		int deptCount = deptCountNum.intValue();
		int userCount = userCountNum.intValue();
		int audit = auditNum.intValue();
		int notAudit = notAuditNum.intValue();
		double deptCountRate = 1 - (double) deptCount / inMaintain;
		double userCountRate = 1 - (double) userCount / inMaintain;
		double auditRate = (double) audit / inMaintain;
		double notAuditRate = (double) notAudit / inMaintain;
		String deptCountPercentage = String.format("%.1f", deptCountRate * 100);
		String userCountPercentage = String.format("%.1f", userCountRate * 100);
		String auditPercentage = String.format("%.1f", auditRate * 100);
		String notAuditPercentage = String.format("%.1f", notAuditRate * 100);
		int alreadySetDept = inMaintain - deptCount;
		int alreadySetUser = inMaintain - userCount;

		ElevatorPrincipalStatisticsVO epsVO = new ElevatorPrincipalStatisticsVO();
		epsVO.setInMaintain(inMaintain);
		epsVO.setDeptCount(deptCount);
		epsVO.setUserCount(userCount);
		epsVO.setAudit(audit);
		epsVO.setNotAudit(notAudit);
		epsVO.setDeptCountRate(deptCountRate);
		epsVO.setUserCountRate(userCountRate);
		epsVO.setAuditRate(auditRate);
		epsVO.setNotAuditRate(notAuditRate);
		epsVO.setDeptCountPercentage(deptCountPercentage);
		epsVO.setUserCountPercentage(userCountPercentage);
		epsVO.setAuditPercentage(auditPercentage);
		epsVO.setNotAuditPercentage(notAuditPercentage);
		epsVO.setAlreadySetDept(alreadySetDept);
		epsVO.setAlreadySetUser(alreadySetUser);

		return epsVO;
	}

	@Override
	public String downUnsetExcel(Integer unsetType) {
		Integer deptType = 1;
		Integer userType = 2;
		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String timeFormat = sdf.format(d);
		String fileName = null;
		// get excel messages by unsetType
		ElevatorPrincipalQueryDTO queryDTO = new ElevatorPrincipalQueryDTO();
		List<Integer> maintainStatus = new ArrayList<>();
		maintainStatus.add(ElevatorMaintainStatusEnums.CONTRACT_IN_TIME.getId());
		maintainStatus.add(ElevatorMaintainStatusEnums.CONTRACT_OUT_TIME.getId());
		maintainStatus.add(ElevatorMaintainStatusEnums.OUT_TIME_STOP.getId());
		maintainStatus.add(ElevatorMaintainStatusEnums.OUT_TIME_END.getId());
		maintainStatus.add(ElevatorMaintainStatusEnums.OUT_TIME_END_HAS_NEXT.getId());
		maintainStatus.add(ElevatorMaintainStatusEnums.DIS_ENABLE.getId());
		queryDTO.setMaintainStatus(maintainStatus);
		if (!(deptType.equals(unsetType) || userType.equals(unsetType))) {
			throw new ServiceException("下载失败！未选择正确的Excel下载内容类型，请联系系统管理员！");
		}
		if (deptType.equals(unsetType)) {
			queryDTO.setMpDeptStatus(2);
			fileName = "未设置责任组电梯-" + timeFormat;
		}
		if (userType.equals(unsetType)) {
			queryDTO.setMpUserStatus(2);
			fileName = "未设置责任人电梯-" + timeFormat;
		}
		queryDTO.setType(1);
		List<ElevatorPrincipalPageVO> eppVOS = baseMapper.selectElevatorPrincipalPage(queryDTO);
		// write into file
		List<List<String>> rows = new ArrayList<>();
		List<String> title = CollUtil.newArrayList("项目名称", "梯号", "电梯所属维保组", "维保责任人");
		ExcelWriter excelWriter = null;
		for (ElevatorPrincipalPageVO r : eppVOS) {
			List<String> row = new ArrayList<>();
			row.add(r.getBuildingName());
			row.add(r.getElevatorAddress());
			row.add(Func.isNull(r.getPrincipalDeptName()) ? "未分配" : r.getPrincipalDeptName());
			row.add(Func.isNull(r.getPrincipalUserNames()) ? "未分配" : r.getPrincipalUserNames());
			rows.add(row);
		}
		excelWriter = ExcelUtil.getBigWriter(rows.size());

		excelWriter.setColumnWidth(0, 30);
		excelWriter.setColumnWidth(1, 30);
		excelWriter.setColumnWidth(2, 30);
		excelWriter.setColumnWidth(3, 30);

		// 单独设置头部
		excelWriter.writeHeadRow(title);
		// 使用默认头部样式
		excelWriter.write(rows, true);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		excelWriter.flush(bos, true);
		InputStream is = new ByteArrayInputStream(bos.toByteArray());
		String downLink = ossBuilder.template().putFile(BladeOssRuleExt.DIV_FILE_NAME + fileName + ".xlsx", is).getLink();
		excelWriter.close();
		try {
			is.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return downLink;
	}

	@Override
	public List<ElevatorSimpleInfoVO> getElevatorSimpleList(List<Long> elevatorIds) {
		return baseMapper.getElevatorSimpleList(elevatorIds);
	}

	@Override
	public ElevatorSimpleInfoVO getElevatorSimpleInfo(Long elevatorId) {
		List<ElevatorSimpleInfoVO> list = getElevatorSimpleList(Arrays.asList(elevatorId));
		return Func.isEmpty(list) ? null : list.get(0);
	}

	@Override
	public ElevatorHealthVo getElevatorHealthInfo(Long elevatorId, Long partId, Long floorStandIds) {


		ElevatorHealthVo elevatorHealthVo = new ElevatorHealthVo();
		ElevatorDetail elevatorDetail = elevatorDetailService.getOne(Wrappers.<ElevatorDetail>lambdaQuery().eq(ElevatorDetail::getElevatorId, elevatorId));
		if (elevatorDetail == null) {
			return elevatorHealthVo;
		}
		List<Dict> problem = dictService.getList("fault_problem");
		ElevatorScore elevatorScore = elevatorScoreService.getOne(Wrappers.<ElevatorScore>lambdaQuery().eq(ElevatorScore::getElevatorId, elevatorId));

		if (elevatorDetail.getStartDate() != null) {
			Integer days = Convert.toInt(DateUtil.betweenDay(elevatorDetail.getStartDate(), new Date(), true), 0);
			BigDecimal divide = Convert.toBigDecimal(days).divide(Convert.toBigDecimal(365), 1, BigDecimal.ROUND_HALF_UP);
			elevatorHealthVo.setUserYear(divide + "年");
			BigDecimal subtract = Convert.toBigDecimal(100).subtract(Convert.toBigDecimal(elevatorHealthVo.getUserYear()).multiply(Convert.toBigDecimal(1.2)));
			if (elevatorScore != null) {
				BigDecimal subtract1 = Convert.toBigDecimal(100).subtract(elevatorScore.getFaceScore());
				BigDecimal subtract2 = Convert.toBigDecimal(100).subtract(elevatorScore.getFunctionalScore());
				BigDecimal subtract3 = Convert.toBigDecimal(100).subtract(elevatorScore.getLubricatingScore());
				BigDecimal subtract4 = Convert.toBigDecimal(100).subtract(elevatorScore.getMeasurementScore());

				BigDecimal faceScore = Convert.toBigDecimal(0.2).multiply(subtract1);
				BigDecimal functionalScore = Convert.toBigDecimal(0.6).multiply(subtract2);
				BigDecimal lubricatingScore = Convert.toBigDecimal(0.4).multiply(subtract3);
				BigDecimal measurementScore = Convert.toBigDecimal(0.4).multiply(subtract4);
				subtract = subtract.subtract(faceScore).subtract(functionalScore).subtract(lubricatingScore).subtract(measurementScore);
			}
			if (subtract.compareTo(Convert.toBigDecimal(60)) == 1) {
				elevatorHealthVo.setHealthScore(subtract.setScale(0, BigDecimal.ROUND_HALF_UP));
			} else {
				elevatorHealthVo.setHealthScore(Convert.toBigDecimal(60));
			}
		}


		ElevatorSearchDTO disWx = new ElevatorSearchDTO();
		ElevatorSearchDTO disPj = new ElevatorSearchDTO();

		disWx.setStatus(TaskStatusEnum.WX_TO_START.getStatus());
		disWx.setElevatorId(elevatorId);

		disPj.setStatus(TaskStatusEnum.PARTS_TO_START.getStatus());
		disPj.setElevatorId(elevatorId);


		List<ElevatorPlanVo> disWxList = baseMapper.getPlanListWx(disWx);
		List<ElevatorPlanVo> disPjList = baseMapper.getPlanListPj(disPj);

		if (partId == null) {

			List<ElevatorPlanVo> resultList = new ArrayList<>(50);

			ElevatorSearchDTO by = new ElevatorSearchDTO();
			ElevatorSearchDTO wx = new ElevatorSearchDTO();
			ElevatorSearchDTO kr = new ElevatorSearchDTO();
			ElevatorSearchDTO pj = new ElevatorSearchDTO();
			//获取保养
			by.setStatus(TaskStatusEnum.BY_PROCESSED.getStatus());
			by.setElevatorId(elevatorId);
			List<ElevatorPlanVo> list1 = baseMapper.getPlanListBy(by);
			overdueDateInit(list1);

			//获取维修
			wx.setElevatorId(elevatorId);
			wx.setStatus(TaskStatusEnum.WX_UNDER_WAY.getStatus());
			List<ElevatorPlanVo> list2 = baseMapper.getPlanListWx(wx);

			if (list2.size() > 0) {
				Map<String, List<Dict>> stringListMap = problem.stream().collect(Collectors.groupingBy(Dict::getDictKey));
				for (ElevatorPlanVo elevatorPlanVo : list2) {
					if (StrUtil.isNotEmpty(elevatorPlanVo.getProblemItem())) {
						List<String> problemItemNames = new ArrayList<>(16);
						String[] split = elevatorPlanVo.getProblemItem().split(",");
						for (String str : split) {
							List<Dict> dicts = stringListMap.get(str);
							if (dicts != null && dicts.size() > 0) {
								problemItemNames.add(Convert.toStr(dicts.get(0).getDictValue(), ""));
							}

						}
						elevatorPlanVo.setProblemItemNames(problemItemNames);
					}
				}
			}

			//获取困人
			kr.setElevatorId(elevatorId);
			kr.setStatus(TaskStatusEnum.JY_PROCESSED.getStatus());
			List<ElevatorPlanVo> list3 = baseMapper.getPlanListKr(kr);

			//获取配件
			pj.setElevatorId(elevatorId);
			pj.setStatus(TaskStatusEnum.PARTS_CHANGE.getStatus());
			List<ElevatorPlanVo> list4 = baseMapper.getPlanListPj(pj);

			resultList.addAll(list1);
			resultList.addAll(list2);
			resultList.addAll(list3);
			resultList.addAll(list4);
			resultList.sort(Comparator.comparing(ElevatorPlanVo::getTime).reversed());

			if (resultList.size() > 0) {
				elevatorHealthVo.setStatus(StatusEnum.DISABLE.getId());
				//功能分计算
				List<ElevatorPlanVo> functionals = new ArrayList<>(3);
				functionals.addAll(list2);
				functionals.addAll(list4);
				functionals.addAll(disWxList);
				functionals.addAll(disPjList);
				if (functionals.size() > 0) {
					elevatorHealthVo.setFunctionalScoreCounts(functionals.size());
					elevatorHealthVo.setUnDisposeCounts(functionals.size());
					BigDecimal subtract = Convert.toBigDecimal(100).subtract(Convert.toBigDecimal(functionals.size()).multiply(Convert.toBigDecimal(10)));
					Integer integer = Convert.toInt(subtract.toString());
					elevatorHealthVo.setFunctionalScore(Convert.toBigDecimal(integer < 60 ? 60 : integer));
				}
				//健康分计算
				BigDecimal subtract = elevatorHealthVo.getHealthScore().subtract(Convert.toBigDecimal(functionals.size()).multiply(Convert.toBigDecimal(10)));
				Integer integer = Convert.toInt(subtract.toString());
				elevatorHealthVo.setHealthScore(Convert.toBigDecimal(integer < 60 ? 60 : integer));
			} else {
				elevatorHealthVo.setStatus(StatusEnum.ENABLE.getId());
				//查询完成的工单
				by.setStatus(TaskStatusEnum.BY_SIGN.getStatus());
				wx.setStatus(TaskStatusEnum.WX_SIGN_FINISH.getStatus());
				kr.setStatus(TaskStatusEnum.JY_RESCUE.getStatus());
				pj.setStatus(TaskStatusEnum.PARTS_FINISH.getStatus());
				List<ElevatorPlanVo> list5 = baseMapper.getPlanListBy(by);
				by.setStatus(TaskStatusEnum.BY_MAINTAIN_SIGN.getStatus());
				List<ElevatorPlanVo> list9 = baseMapper.getPlanListBy(by);
				list5.addAll(list9);
				overdueDateInit(list5);

				List<ElevatorPlanVo> list6 = baseMapper.getPlanListWx(wx);
				List<ElevatorPlanVo> list7 = baseMapper.getPlanListKr(kr);
				List<ElevatorPlanVo> list8 = baseMapper.getPlanListPj(pj);

				//已完成工单计算健康分（包含待开始的工单）
				Map<String, List<Dict>> stringListMap = problem.stream().collect(Collectors.groupingBy(Dict::getDictKey));
				for (ElevatorPlanVo elevatorPlanVo : list6) {
					if (StrUtil.isNotEmpty(elevatorPlanVo.getProblemItem())) {
						List<String> problemItemNames = new ArrayList<>(16);
						String[] split = elevatorPlanVo.getProblemItem().split(",");
						for (String str : split) {
							if (StrUtil.isEmpty(str)) {
								continue;
							}
							problemItemNames.add(Convert.toStr(stringListMap.get(str).get(0).getDictValue(), ""));
						}
						elevatorPlanVo.setProblemItemNames(problemItemNames);
					}
				}
				resultList.addAll(list5);
				resultList.addAll(list6);
				resultList.addAll(list7);
				resultList.addAll(list8);


				//功能分计算
				List<ElevatorPlanVo> functionals = new ArrayList<>(3);
				functionals.addAll(disWxList);
				functionals.addAll(disPjList);
				if (functionals.size() > 0) {
					elevatorHealthVo.setFunctionalScoreCounts(functionals.size());
					elevatorHealthVo.setUnDisposeCounts(functionals.size());
					BigDecimal subtract = Convert.toBigDecimal(100).subtract(Convert.toBigDecimal(functionals.size()).multiply(Convert.toBigDecimal(10)));
					Integer integer = Convert.toInt(subtract.toString());
					elevatorHealthVo.setFunctionalScore(Convert.toBigDecimal(integer < 60 ? 60 : integer));
				}
				//健康分计算
				BigDecimal subtract = elevatorHealthVo.getHealthScore().subtract(Convert.toBigDecimal(functionals.size()).multiply(Convert.toBigDecimal(10)));
				Integer integer = Convert.toInt(subtract.toString());
				elevatorHealthVo.setHealthScore(Convert.toBigDecimal(integer < 60 ? 60 : integer));
			}

			//处理执行人
			for (ElevatorPlanVo elevatorPlanVo : resultList) {
				elevatorPlanVo.setList(maintainPlanContentUserService.listUserByPlan(elevatorPlanVo.getPlanId()));
			}
			elevatorHealthVo.setList(resultList);
		} else {
			List<ElevatorPartWorkVo> resultList = new ArrayList<>(16);
			ElevatorSearchDTO by = new ElevatorSearchDTO();
			ElevatorSearchDTO wx = new ElevatorSearchDTO();
			ElevatorSearchDTO pj = new ElevatorSearchDTO();
			by.setPartId(partId);
			by.setElevatorId(elevatorId);
			List<ElevatorPartWorkVo> list1 = baseMapper.getWorkListBy(by);
			if (list1.size() > 0) {
				List<Long> ids = list1.stream().map(ElevatorPartWorkVo::getId).collect(Collectors.toList());
				List<MaintainCheckRecord> workImageList = baseMapper.getWorkImageList(ids);
				Map<Long, List<MaintainCheckRecord>> listMap = workImageList.stream().collect(Collectors.groupingBy(MaintainCheckRecord::getCheckHistoryId));
				for (ElevatorPartWorkVo elevatorPartWorkVo : list1) {
					List<MaintainCheckRecord> maintainCheckRecords = listMap.get(elevatorPartWorkVo.getId());
					if (maintainCheckRecords != null && maintainCheckRecords.size() > 0) {
						List<JSONObject> jsonObjects = maintainCheckRecords.stream().map(MaintainCheckRecord::getRecordDataValue).collect(Collectors.toList());
						elevatorPartWorkVo.setRecordDataValues(jsonObjects);
					}
				}

			}
			wx.setPartId(partId);
			wx.setFloorStandIds(floorStandIds);
			wx.setElevatorId(elevatorId);
			pj.setPartId(partId);
			pj.setElevatorId(elevatorId);
			List<ElevatorPartWorkVo> list2 = baseMapper.getWorkListWx(wx);
			if (list2.size() > 0) {
				Map<String, List<Dict>> stringListMap = problem.stream().collect(Collectors.groupingBy(Dict::getDictKey));
				for (ElevatorPartWorkVo elevatorPartWorkVo : list2) {
					if (StrUtil.isNotEmpty(elevatorPartWorkVo.getProblemItem())) {
						List<String> problemItemNames = new ArrayList<>(16);
						String[] split = elevatorPartWorkVo.getProblemItem().split(",");
						for (String str : split) {
							List<Dict> dicts = stringListMap.get(str);
							if (dicts != null && dicts.size() > 0) {
								problemItemNames.add(Convert.toStr(dicts.get(0).getDictValue(), ""));
							}

						}
						elevatorPartWorkVo.setProblemItemNames(problemItemNames);
					}
				}
			}


			List<ElevatorPartWorkVo> list3 = baseMapper.getWorkListPj(pj);
			resultList.addAll(list1);
			resultList.addAll(list2);
			resultList.addAll(list3);
			resultList.sort(Comparator.comparing(ElevatorPartWorkVo::getCreateTime).reversed());

			elevatorHealthVo.setWorkVoList(resultList);
		}

		if (elevatorScore != null) {
			elevatorHealthVo.setFaceScore(elevatorScore.getFaceScore());
			elevatorHealthVo.setFunctionalScore(elevatorScore.getFunctionalScore());
			elevatorHealthVo.setLubricatingScore(elevatorScore.getLubricatingScore());
			elevatorHealthVo.setMeasurementScore(elevatorScore.getMeasurementScore());
		}

		return elevatorHealthVo;
	}

	@Override
	public NewElevatorPartVO getNewElevatorPartVO(Long elevatorId, Long partId) {
		// 1. 数据校验, elevator id 必须传
		if (Func.isNull(elevatorId)) {
			throw new ServiceException("错误，必须传入电梯id");
		}
		// 电梯基础信息
		NewElevatorPartVO newElevatorPartVO = baseMapper.getNewElevatorPartVO(elevatorId);
		newElevatorPartVO.setPartId(partId);
		// 计算年限并赋值
		if (!Func.isNull(newElevatorPartVO.getStartDate())) {
			Date startDate = newElevatorPartVO.getStartDate();
			long milliseconds = System.currentTimeMillis() - startDate.getTime();
			double years = milliseconds / (1000.0 * 60 * 60 * 24 * 365);
			String usedYear = String.format("%.1f", years);
			newElevatorPartVO.setUsedYear(usedYear);
		}

		// 2 partId 不为null, 根据需求条件关联查询最近该part工单：有则显示无则返回第一个及电梯使用时间
		if (!Func.isNull(partId)) {
			String brand = baseMapper.getPartName(partId);
			newElevatorPartVO.setBrand(brand);
			// 由配件工单 获取该梯全部配件申请
			// 2023-11-23 按第最近一个DESC，截取 parts 集合
			// 获取该梯全部配件申请，按倒序第一个则ASC排列，截取 parts 集合
			List<MaintainPlanContent> planList = planContentService.list(new LambdaQueryWrapper<MaintainPlanContent>()
				.eq(MaintainPlanContent::getElevatorId, elevatorId)
				.eq(BaseEntity::getIsDeleted, 0)
				.eq(MaintainPlanContent::getTypeStatus, MaintainPlanContentEnum.MAINTAIN_PARTS.getId())
				.orderByDesc(BaseEntity::getCreateTime)
			);
			// 若没有该工单，则直接返回
			if (Func.isEmpty(planList)) {
				newElevatorPartVO.setCurrentTime(newElevatorPartVO.getStartDate());
				// 直接返回
				return newElevatorPartVO;
			}

			//  配件申请集合只获取并比对 ids 最后一个
			for (int i = 0; i < planList.size(); i++) {
				MaintainPlanContent maintainPlanContent = planList.get(i);
				// 配件工作工单申请列表，获取当前工单的PartsWork对象
				MaintainPartsWork tempWork = maintainPartsWorkService.getOne(
					new LambdaQueryWrapper<MaintainPartsWork>()
						.eq(MaintainPartsWork::getPlanId, maintainPlanContent.getId())
						.eq(BaseEntity::getIsDeleted, 0)
				);

				// 当存在该工单
				if (!Func.isNull(tempWork)) {
					// 获取部件 id 集合, 一般情况下, 最下级的id 会位于最后一个
					String partsId = tempWork.getPartsId();
					// 转换为数组, 并由最后一个比对
					List<Long> ids = Arrays.stream(partsId.split(","))
						.map(Long::parseLong)
						.collect(Collectors.toList());

					if (Func.isNotEmpty(ids)) {
						Long current = ids.get(ids.size() - 1);
						// 若是这个工单, 2023-11-13 拆分字段处理
						if (current.equals(partId)) {
							// 型号
							String partsModel = tempWork.getPartsModel();
							String[] partsModelArrays = partsModel.split(";");
							// 依次赋值品牌，型号，规格，严格插入，一定会是 3个
							if (partsModelArrays.length >= 3) {
								String specsMessages = "";
								String[] tempBrand = partsModelArrays[0].split(":");
								// 品牌
								if (tempBrand.length > 1) {
									newElevatorPartVO.setBrand(tempBrand[1]);
									specsMessages = specsMessages + tempBrand[1] + ";";
								} else {
									newElevatorPartVO.setBrand(tempBrand[0]);
									specsMessages = specsMessages + tempBrand[0] + ";";
								}
								String[] tempModel = partsModelArrays[1].split(":");
								// 型号
								if (tempModel.length > 1) {
									newElevatorPartVO.setModel(tempModel[1]);
									specsMessages = specsMessages + tempModel[1] + ";";
								} else {
									newElevatorPartVO.setModel(tempModel[0]);
									specsMessages = specsMessages + tempModel[0] + ";";
								}
								String[] tempSpecs = partsModelArrays[2].split(":");
								// 规格
								if (tempSpecs.length > 1) {
									newElevatorPartVO.setSpecs(tempSpecs[1]);
									specsMessages = specsMessages + tempSpecs[1] + ";";
								} else {
									newElevatorPartVO.setSpecs(tempSpecs[0]);
									specsMessages = specsMessages + tempSpecs[0] + ";";
								}
								newElevatorPartVO.setSpecsMessage(specsMessages);
							}
							newElevatorPartVO.setCurrentTime(tempWork.getUpdateTime());
							return newElevatorPartVO;
						}
					}
				}
			}
		}
		return newElevatorPartVO;
	}

	@Override
	public ElevatorPartWorkVo getElevatorPartWorkDetailImage(Long planId) {
		MaintainPlanContent currentPlan = planContentService.getById(planId);
		if (Func.isNull(currentPlan)) {
			throw new ServiceException("查询失败，不存在该工单");
		}
		Integer typeStatus = currentPlan.getTypeStatus();
		ElevatorPartWorkVo result = new ElevatorPartWorkVo();
		if (typeStatus.equals(MaintainPlanContentEnum.MAINTAIN_BY.getId())) {
			// 执行 MaintainPlanContentEnum.MAINTAIN_BY 对应的操作
			// 复用 冲哥的代码
			ElevatorPartWorkVo byDetail = baseMapper.getWorkListByDetail(planId);
			if (!Func.isNull(byDetail)) {
				Long byDetailId = byDetail.getId();
				List<Long> ids = new ArrayList<>();
				ids.add(byDetailId);
				List<MaintainCheckRecord> workImageList = baseMapper.getWorkImageList(ids);
				Map<Long, List<MaintainCheckRecord>> listMap = workImageList.stream().collect(Collectors.groupingBy(MaintainCheckRecord::getCheckHistoryId));
				List<MaintainCheckRecord> maintainCheckRecords = listMap.get(byDetailId);
				if (maintainCheckRecords != null && maintainCheckRecords.size() > 0) {
					List<JSONObject> jsonObjects = maintainCheckRecords.stream().map(MaintainCheckRecord::getRecordDataValue).collect(Collectors.toList());
					byDetail.setRecordDataValues(jsonObjects);
				}
			}
			result = byDetail;
		} else if (typeStatus.equals(MaintainPlanContentEnum.MAINTAIN_WX.getId())) {
			// 执行 MaintainPlanContentEnum.MAINTAIN_WX 对应的操作
			ElevatorPartWorkVo wxDetail = baseMapper.getWorkListWxDetail(planId);
			result = wxDetail;
		} else {
			// 如果没有匹配的情况，则执行默认操作
			ElevatorPartWorkVo partDetail = baseMapper.getWorkListPartDetail(planId);
			result = partDetail;

		}
		return result;
	}

	@Override
	public List<ElevatorPlanVo> planListByAndWx(Long elevatorId) {
		List<ElevatorPlanVo> list = new ArrayList<>(16);
		ElevatorSearchDTO disWx = new ElevatorSearchDTO();
		ElevatorSearchDTO disPj = new ElevatorSearchDTO();

		disWx.setStatus(TaskStatusEnum.WX_TO_START.getStatus());
		disWx.setElevatorId(elevatorId);

		disPj.setStatus(TaskStatusEnum.PARTS_TO_START.getStatus());
		disPj.setElevatorId(elevatorId);

		List<ElevatorPlanVo> disWxList = baseMapper.getPlanListWx(disWx);
		List<ElevatorPlanVo> disPjList = baseMapper.getPlanListPj(disPj);

		//获取维修
		disWx.setElevatorId(elevatorId);
		disWx.setStatus(TaskStatusEnum.WX_UNDER_WAY.getStatus());
		List<ElevatorPlanVo> list2 = baseMapper.getPlanListWx(disWx);
		list2.addAll(disWxList);


		disPj.setElevatorId(elevatorId);
		disPj.setStatus(TaskStatusEnum.PARTS_CHANGE.getStatus());
		List<ElevatorPlanVo> list4 = baseMapper.getPlanListPj(disPj);
		list4.addAll(disPjList);

		if (list2.size() > 0) {
			List<Dict> problem = dictService.getList("fault_problem");
			Map<String, List<Dict>> stringListMap = problem.stream().collect(Collectors.groupingBy(Dict::getDictKey));
			for (ElevatorPlanVo elevatorPlanVo : list2) {
				if (StrUtil.isNotEmpty(elevatorPlanVo.getProblemItem())) {
					List<String> problemItemNames = new ArrayList<>(16);
					String[] split = elevatorPlanVo.getProblemItem().split(",");
					for (String str : split) {
						List<Dict> dicts = stringListMap.get(str);
						if (dicts != null && dicts.size() > 0) {
							problemItemNames.add(Convert.toStr(dicts.get(0).getDictValue(), ""));
						}

					}
					elevatorPlanVo.setProblemItemNames(problemItemNames);
				}
			}
		}

		list.addAll(list2);
		list.addAll(list4);

		list.sort(Comparator.comparing(ElevatorPlanVo::getTime).reversed());
		return list;
	}

	@Override
	public List<Dict> driverModeFieldSelect(String code, String driverModeCode, String driverModeKey) {
		List<Dict> dictList = new ArrayList<>();
		dictList = dictService.getList(code);
		if (ObjectUtil.isNotEmpty(driverModeCode)) {
			if (driverModeCode.equals("3110") || driverModeCode.equals("3120") || driverModeCode.equals("3130")) {
				dictList = dictService.getList("controlModeA");
			} else if (driverModeCode.equals("3220") || driverModeCode.equals("3210")) {
				dictList = dictService.getList("controlModeB");
			} else if (driverModeCode.equals("3410") || driverModeCode.equals("3420") || driverModeCode.equals("3430")) {
				if (ObjectUtil.isNotEmpty(driverModeKey)) {
					if (driverModeKey.equals("1") || driverModeKey.equals("2")) {
						dictList = dictService.getList("controlModeA");
					} else {
						dictList = dictService.getList("controlModeB");
					}
				}
			}
		}
		return dictList;
	}


	/**
	 * 逾期文案初始化
	 *
	 * @param list1
	 */
	private void overdueDateInit(List<ElevatorPlanVo> list1) {
		for (ElevatorPlanVo elevatorPlanVo : list1) {
			if (elevatorPlanVo.getTypeStatus().equals(MaintainPlanContentEnum.MAINTAIN_BY.getId())) {
				if (elevatorPlanVo.getStatus().equals(TaskStatusEnum.BY_SIGN.getStatus()) || elevatorPlanVo.getStatus().equals(TaskStatusEnum.BY_MAINTAIN_SIGN.getStatus())) {
					if (elevatorPlanVo.getAuditType().equals(PlanAuditTypeEnum.AUDIT.getStatus()) && cn.hutool.core.util.ObjectUtil.isNotEmpty(elevatorPlanVo.getOverdueDate())) {
						long maintainSignatureTime = DateUtil.parse(DateUtil.format(elevatorPlanVo.getMaintainSignatureTime(), "yyyy-MM-dd")).getTime();
						long overdueDate = elevatorPlanVo.getOverdueDate().getTime();
						if (maintainSignatureTime > overdueDate) {
							long betweenDay = DateUtil.between(elevatorPlanVo.getOverdueDate(), elevatorPlanVo.getMaintainSignatureTime(), DateUnit.DAY);
							elevatorPlanVo.setOverdueDateDesc("逾期" + betweenDay + "天");
						}
					}

					long betweenDay = DateUtil.between(elevatorPlanVo.getTime(), elevatorPlanVo.getMaintainSignatureTime(), DateUnit.DAY);
					if (betweenDay > 0) {
						if (elevatorPlanVo.getTime().compareTo(elevatorPlanVo.getMaintainSignatureTime()) < 0) {
							elevatorPlanVo.setTimeliness("超时" + betweenDay + "天");
						}
					} else if (betweenDay == 0) {
						elevatorPlanVo.setTimeliness(WorkTrackStatusEnum.IN_TIME.getTypeName());
					}

				} else {
					if (elevatorPlanVo.getAuditType().equals(PlanAuditTypeEnum.AUDIT.getStatus()) && cn.hutool.core.util.ObjectUtil.isNotEmpty(elevatorPlanVo.getOverdueDate())) {
						long planDate = elevatorPlanVo.getTime().getTime();
						long overdueDate = elevatorPlanVo.getOverdueDate().getTime();
						long nowDate = DateUtil.parse(DateUtil.today()).getTime();
						if (planDate <= nowDate && nowDate > overdueDate) {
							long betweenDay = DateUtil.between(elevatorPlanVo.getOverdueDate(), DateUtil.date(), DateUnit.DAY);
							elevatorPlanVo.setOverdueDateDesc("逾期" + betweenDay + "天");
						}
					}
					long betweenDay = DateUtil.between(elevatorPlanVo.getTime(), new Date(), DateUnit.DAY);
					if (betweenDay > 0) {
						if (elevatorPlanVo.getTime().compareTo(DateUtil.date()) < 0) {
							elevatorPlanVo.setTimeliness("超时" + betweenDay + "天");
						}
					}
				}
			}
		}
	}


	/**
	 * 获取重复的
	 *
	 * @param list1:数据库数据
	 * @param list2       新增的数据
	 * @return
	 */
	private List<PartWordUrlVo> filterExis(List<PartWordUrlVo> list1, List<PartWordUrlVo> list2) {
		if (list1 == null || list1.size() == 0) {
			return list2;
		} else {
			list1 = JSON.parseArray(JSON.toJSONString(list1), PartWordUrlVo.class);
		}
		List<PartWordUrlVo> resultList = new ArrayList<>(16);
		List<String> urls = list1.stream().map(PartWordUrlVo::getUrl).collect(Collectors.toList());
		for (PartWordUrlVo partWordUrlVo : list2) {
			if (!urls.contains(partWordUrlVo.getUrl())) {
				resultList.add(partWordUrlVo);
			}
		}
		return resultList;
	}


	/**
	 * 电梯完整度计算
	 *
	 * @param elevator
	 * @param elevatorSaveDto
	 */
	private void elevatorIntact(ElevatorDetailDTO elevatorSaveDto, Elevator elevator) {
		//非年审
		if (elevatorSaveDto.getUseType() == 1) {
			//计算类型位置
			elevator.setLwIntact(Convert.toBigDecimal(1));

			//计算维保信息
			Integer wbCounts = 2;
			Integer saveWbCounts = 0;
			if (StrUtil.isNotEmpty(elevatorSaveDto.getWbPhone())) {
				saveWbCounts = saveWbCounts + 1;
			}
			if (elevatorSaveDto.getWbPhoneImg() != null && elevatorSaveDto.getWbPhoneImg().size() > 0) {
				saveWbCounts = saveWbCounts + 1;
			}
			if (saveWbCounts > 0) {
				BigDecimal bigDecimal2 = Convert.toBigDecimal(saveWbCounts).divide(Convert.toBigDecimal(wbCounts), 2, BigDecimal.ROUND_HALF_UP);
				elevator.setWbIntact(bigDecimal2);
			} else {
				elevator.setWbIntact(Convert.toBigDecimal(0));
			}
			//计算设备技术完整性
			elevator.setSbJsIntact(Convert.toBigDecimal(1));
			ElevatorFieldV fieldV = elevatorSaveDto.getFieldV();
			Long driveModeId = fieldV.getDriveModeId();
			if (driveModeId.equals(1441306947313549315L) || driveModeId.equals(1441306947313549317L) || driveModeId.equals(1441306947313549328L) || driveModeId.equals(1441306947313549320L) || driveModeId.equals(1441306947313549322L) || driveModeId.equals(1441306947162554369L)) {
				//计算维保信息
				Integer sbJsCounts = 9;
				Integer saveSbJsCounts = 6;
				if (elevatorSaveDto.getFloorTier() != null && elevatorSaveDto.getFloorTier().size() > 0 && elevatorSaveDto.getFloorTier().stream().filter(o -> o.getIsHas() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				if (elevatorSaveDto.getFloorPlatforms() != null && elevatorSaveDto.getFloorPlatforms().size() > 0 && elevatorSaveDto.getFloorPlatforms().stream().filter(o -> o.getIsHas() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				if (elevatorSaveDto.getFloorDoors() != null && elevatorSaveDto.getFloorDoors().size() > 0 && elevatorSaveDto.getFloorDoors().stream().filter(o -> o.getIsBackDoor() == true || o.getIsFrontDoor() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				BigDecimal bigDecimal2 = Convert.toBigDecimal(saveSbJsCounts).divide(Convert.toBigDecimal(sbJsCounts), 2, BigDecimal.ROUND_HALF_UP);
				elevator.setSbJsIntact(bigDecimal2);
			} else if (driveModeId.equals(1441306947313549333L) || driveModeId.equals(1441306947313549326L) || driveModeId.equals(1441306947313549336L)) {
				Integer sbJsCounts = 12;
				Integer saveSbJsCounts = 9;
				if (elevatorSaveDto.getFloorTier() != null && elevatorSaveDto.getFloorTier().size() > 0 && elevatorSaveDto.getFloorTier().stream().filter(o -> o.getIsHas() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				if (elevatorSaveDto.getFloorPlatforms() != null && elevatorSaveDto.getFloorPlatforms().size() > 0 && elevatorSaveDto.getFloorPlatforms().stream().filter(o -> o.getIsHas() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				if (elevatorSaveDto.getFloorDoors() != null && elevatorSaveDto.getFloorDoors().size() > 0 && elevatorSaveDto.getFloorDoors().stream().filter(o -> o.getIsBackDoor() == true || o.getIsFrontDoor() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				BigDecimal bigDecimal2 = Convert.toBigDecimal(saveSbJsCounts).divide(Convert.toBigDecimal(sbJsCounts), 2, BigDecimal.ROUND_HALF_UP);
				elevator.setSbJsIntact(bigDecimal2);
			}
			//出厂
			elevator.setCcIntact(Convert.toBigDecimal(1));

			//使用信息
			if (StrUtil.isNotEmpty(elevatorSaveDto.getSecurityGuardName())) {
				elevator.setSyIntact(Convert.toBigDecimal(1));
			} else {
				elevator.setSyIntact(Convert.toBigDecimal(0));
			}

			//安装信息
			if (elevatorSaveDto.getAzCheckBeginDate() != null) {
				elevator.setAzIntact(Convert.toBigDecimal(1));
			} else {
				elevator.setAzIntact(Convert.toBigDecimal(0));
			}

			//计算保险信息
			Integer bxCounts = 3;
			Integer saveBxCounts = 0;
			if (elevatorSaveDto.getBxCompanyId() != null) {
				saveBxCounts = saveBxCounts + 1;
			}
			if (elevatorSaveDto.getBxCompanyEndDate() != null) {
				saveBxCounts = saveBxCounts + 1;
			}
			if (elevatorSaveDto.getBxExtUrl() != null && elevatorSaveDto.getBxExtUrl().size() > 0) {
				saveBxCounts = saveBxCounts + 1;
			}
			if (saveBxCounts > 0) {
				BigDecimal bigDecimal = Convert.toBigDecimal(saveBxCounts).divide(Convert.toBigDecimal(bxCounts), 2, BigDecimal.ROUND_HALF_UP);
				elevator.setBxIntact(bigDecimal);
			} else {
				elevator.setBxIntact(Convert.toBigDecimal(0));
			}
			// 2024-10-31 应远哥要求，非年审保险和zc完整度设置1
			elevator.setBxIntact(Convert.toBigDecimal(1));
			elevator.setSbZcIntact(Convert.toBigDecimal(1));

			//梯无忧
			if (elevatorSaveDto.getElevatorNumImg() != null && elevatorSaveDto.getElevatorNumImg().size() > 0) {
				elevator.setTwyIntact(Convert.toBigDecimal(1));
			} else {
				elevator.setTwyIntact(Convert.toBigDecimal(0));
			}

			//电梯结构
			ElevatorPartsStructureTemplateRelation detail = elevatorPartsStructureTemplateRelationService.getOne(Wrappers.<ElevatorPartsStructureTemplateRelation>lambdaQuery().eq(ElevatorPartsStructureTemplateRelation::getElevatorId, elevator.getId()), false);
			if (detail != null && detail.getStructureTemplateId() != null) {
				elevator.setJgIntact(Convert.toBigDecimal(1));
			} else {
				elevator.setJgIntact(Convert.toBigDecimal(0));
			}
		} else {

			//年审
			//计算类型位置
			elevator.setLwIntact(Convert.toBigDecimal(1));

			//计算维保信息
			Integer wbCounts = 3;
			Integer saveWbCounts = 0;
			if (StrUtil.isNotEmpty(elevatorSaveDto.getWbPhone())) {
				saveWbCounts = saveWbCounts + 1;
			}
			if (elevatorSaveDto.getWbPhoneImg() != null && elevatorSaveDto.getWbPhoneImg().size() > 0) {
				saveWbCounts = saveWbCounts + 1;
			}
			if (elevatorSaveDto.getWbExtUrl() != null && elevatorSaveDto.getWbExtUrl().size() > 0) {
				saveWbCounts = saveWbCounts + 1;
			}
			if (saveWbCounts > 0) {
				BigDecimal bigDecimal2 = Convert.toBigDecimal(saveWbCounts).divide(Convert.toBigDecimal(wbCounts), 2, BigDecimal.ROUND_HALF_UP);
				elevator.setWbIntact(bigDecimal2);
			} else {
				elevator.setWbIntact(Convert.toBigDecimal(0));
			}

			//计算设备技术完整性
			elevator.setSbJsIntact(Convert.toBigDecimal(1));
			ElevatorFieldV fieldV = elevatorSaveDto.getFieldV();
			Long driveModeId = fieldV.getDriveModeId();
			//计算设备技术完整性

			if (driveModeId.equals(1441306947313549315L) || driveModeId.equals(1441306947313549317L) || driveModeId.equals(1441306947313549328L) || driveModeId.equals(1441306947313549320L) || driveModeId.equals(1441306947313549322L) || driveModeId.equals(1441306947162554369L)) {
				//计算维保信息
				Integer sbJsCounts = 9;
				Integer saveSbJsCounts = 6;
				if (elevatorSaveDto.getFloorTier() != null && elevatorSaveDto.getFloorTier().size() > 0 && elevatorSaveDto.getFloorTier().stream().filter(o -> o.getIsHas() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				if (elevatorSaveDto.getFloorPlatforms() != null && elevatorSaveDto.getFloorPlatforms().size() > 0 && elevatorSaveDto.getFloorPlatforms().stream().filter(o -> o.getIsHas() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				if (elevatorSaveDto.getFloorDoors() != null && elevatorSaveDto.getFloorDoors().size() > 0 && elevatorSaveDto.getFloorDoors().stream().filter(o -> o.getIsBackDoor() == true || o.getIsFrontDoor() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				BigDecimal bigDecimal2 = Convert.toBigDecimal(saveSbJsCounts).divide(Convert.toBigDecimal(sbJsCounts), 2, BigDecimal.ROUND_HALF_UP);
				elevator.setSbJsIntact(bigDecimal2);
			} else if (driveModeId.equals(1441306947313549333L) || driveModeId.equals(1441306947313549326L) || driveModeId.equals(1441306947313549336L)) {
				Integer sbJsCounts = 12;
				Integer saveSbJsCounts = 9;
				if (elevatorSaveDto.getFloorTier() != null && elevatorSaveDto.getFloorTier().size() > 0 && elevatorSaveDto.getFloorTier().stream().filter(o -> o.getIsHas() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				if (elevatorSaveDto.getFloorPlatforms() != null && elevatorSaveDto.getFloorPlatforms().size() > 0 && elevatorSaveDto.getFloorPlatforms().stream().filter(o -> o.getIsHas() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				if (elevatorSaveDto.getFloorDoors() != null && elevatorSaveDto.getFloorDoors().size() > 0 && elevatorSaveDto.getFloorDoors().stream().filter(o -> o.getIsBackDoor() == true || o.getIsFrontDoor() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				BigDecimal bigDecimal2 = Convert.toBigDecimal(saveSbJsCounts).divide(Convert.toBigDecimal(sbJsCounts), 2, BigDecimal.ROUND_HALF_UP);
				elevator.setSbJsIntact(bigDecimal2);
			}

			Integer bxCounts = 3;
			Integer saveBxCounts = 0;
			if (StrUtil.isNotEmpty(elevatorSaveDto.getBxCompanyId())) {
				saveBxCounts = saveBxCounts + 1;
			}
			if (elevatorSaveDto.getBxCompanyEndDate() != null) {
				saveBxCounts = saveBxCounts + 1;
			}
			if (elevatorSaveDto.getBxExtUrl() != null && elevatorSaveDto.getBxExtUrl().size() > 0) {
				saveBxCounts = saveBxCounts + 1;
			}
			if (saveBxCounts > 0) {
				BigDecimal bigDecimal = Convert.toBigDecimal(saveBxCounts).divide(Convert.toBigDecimal(bxCounts), 2, BigDecimal.ROUND_HALF_UP);
				elevator.setBxIntact(bigDecimal);
			} else {
				elevator.setBxIntact(Convert.toBigDecimal(0));
			}


			//设备注册信息
			Integer sbZcCounts = 4;
			Integer saveSbZcCounts = 0;
			if (StrUtil.isNotEmpty(elevatorSaveDto.getPrivateNum())) {
				saveSbZcCounts = saveSbZcCounts + 1;
			}
			if (StrUtil.isNotEmpty(elevatorSaveDto.getEquipmentRegisterNumber())) {
				saveSbZcCounts = saveSbZcCounts + 1;
			}
			if (StrUtil.isNotEmpty(elevatorSaveDto.getRegisterNumber())) {
				saveSbZcCounts = saveSbZcCounts + 1;
			}
			if (elevatorSaveDto.getCertificateLists() != null && elevatorSaveDto.getCertificateLists().size() > 0) {
				List<ElevatorAttachmentHistory> list = elevatorSaveDto.getCertificateLists().stream().filter(o -> o.getStatus() == ElevatorAttachmentEnum.IMG.getStatus()).collect(Collectors.toList());
				if (list.size() > 0) {
					saveSbZcCounts = saveSbZcCounts + 1;
				}
			}
			if (saveSbZcCounts > 0) {
				BigDecimal bigDecimal3 = Convert.toBigDecimal(saveSbZcCounts).divide(Convert.toBigDecimal(sbZcCounts), 2, BigDecimal.ROUND_HALF_UP);
				elevator.setSbZcIntact(bigDecimal3);
			} else {
				elevator.setSbZcIntact(Convert.toBigDecimal(0));
			}

			//出厂
			elevator.setCcIntact(Convert.toBigDecimal(1));

			//使用信息
			if (StrUtil.isNotEmpty(elevatorSaveDto.getSecurityGuardName())) {
				elevator.setSyIntact(Convert.toBigDecimal(1));
			} else {
				elevator.setSyIntact(Convert.toBigDecimal(0));
			}
		}
		//安装信息
		if (elevatorSaveDto.getAzCheckBeginDate() != null) {
			elevator.setAzIntact(Convert.toBigDecimal(1));
		} else {
			elevator.setAzIntact(Convert.toBigDecimal(0));
		}

		//梯无忧
		if (elevatorSaveDto.getElevatorNumImg() != null && elevatorSaveDto.getElevatorNumImg().size() > 0) {
			elevator.setTwyIntact(Convert.toBigDecimal(1));
		} else {
			elevator.setTwyIntact(Convert.toBigDecimal(0));
		}

		//电梯结构
		ElevatorPartsStructureTemplateRelation detail = elevatorPartsStructureTemplateRelationService.getOne(Wrappers.<ElevatorPartsStructureTemplateRelation>lambdaQuery().eq(ElevatorPartsStructureTemplateRelation::getElevatorId, elevator.getId()), false);
		if (detail != null && detail.getStructureTemplateId() != null) {
			elevator.setJgIntact(Convert.toBigDecimal(1));
		} else {
			elevator.setJgIntact(Convert.toBigDecimal(0));
		}
	}

	@Override
	public String getModeNameByElevatorId(Long elevatorId) {
		return baseMapper.getModeNameByElevatorId(elevatorId);
	}

	@Override
	public List<ElevatorSimpleInfoVO> getListByBuildingId(Long buildingId) {
		return baseMapper.getListByBuildingId(buildingId);
	}

	/**
	 * 比较电梯层站
	 */
	private boolean floorPlatformsCompare(List<ElevatorFloorVo> oldFloorPlatforms, List<ElevatorFloorVo> floorPlatforms) {
		if (oldFloorPlatforms == null) {
			return Boolean.FALSE;
		}
		List<ElevatorFloorVo> oldFloorList = JSON.parseArray(JSON.toJSONString(oldFloorPlatforms), ElevatorFloorVo.class);
		String oldFloorPlatformsStr = oldFloorList.stream().filter(ElevatorFloorVo::getIsHas).sorted(Comparator.comparing(ElevatorFloorVo::getFloorNum)).map(ElevatorFloorVo::getFloorNum).collect(Collectors.joining("/"));
		String floorPlatformsStr = floorPlatforms.stream().filter(ElevatorFloorVo::getIsHas).sorted(Comparator.comparing(ElevatorFloorVo::getFloorNum)).map(ElevatorFloorVo::getFloorNum).collect(Collectors.joining("/"));
		return Func.equalsSafe(oldFloorPlatformsStr, floorPlatformsStr);
	}

	/**
	 * 比较电梯层门
	 */
	private boolean floorDoorsCompare(List<ElevatorFloorVo> oldFloorDoors, List<ElevatorFloorVo> floorDoors) {
		if (oldFloorDoors == null) {
			return Boolean.FALSE;
		}
		List<ElevatorFloorVo> oldDoorsList = JSON.parseArray(JSON.toJSONString(oldFloorDoors), ElevatorFloorVo.class);
		String oldFloorDoorsStr = oldDoorsList.stream().sorted(Comparator.comparing(ElevatorFloorVo::getFloorNum)).map(o -> String.format("%s_%s_%s", o.getFloorNum(), o.getIsBackDoor(), o.getIsFrontDoor())).collect(Collectors.joining("/"));
		String floorDoorsStr = floorDoors.stream().sorted(Comparator.comparing(ElevatorFloorVo::getFloorNum)).map(o -> String.format("%s_%s_%s", o.getFloorNum(), o.getIsBackDoor(), o.getIsFrontDoor())).collect(Collectors.joining("/"));
		return Func.equalsSafe(oldFloorDoorsStr, floorDoorsStr);
	}

}
